package com.definity.toolkit.storage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.definity.toolkit.service.ServiceException;

@Service
public class BinaryStorageServiceImpl extends StorageServiceImpl<BinaryData, byte[]> implements BinaryStorageService {

	public BinaryStorageServiceImpl() {
		super(BinaryData.class);
	}

	@Override
	@Transactional
	public BinaryData store(BinaryData data, InputStream stream) {
		try {
			File tempFile = File.createTempFile(data.getName(), "tmp");
			IOUtils.copyLarge(stream, new FileOutputStream(tempFile));
			long length = tempFile.length();
			
			data.setBytes(IOUtils.toByteArray(new FileInputStream(tempFile)));
			data.setSize(length);

			FileUtils.forceDelete(tempFile);
		} catch (IOException e) {
			throw new ServiceException("storage", e);
		}
		return save(data);
	}
	
	@Override
	@Transactional
	public BinaryData update(BinaryData data) {
		return save(data);
	}

	@Override
	public byte[] getContent(BinaryData data) {
		return data.getBytes();
	}

}
